package com.zkk.web;

import com.alibaba.fastjson.JSON;
import com.zkk.pojo.User;
import com.zkk.service.UserService;
import com.zkk.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;
@WebServlet("/login")
public class loginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String telephone = req.getParameter("telephone");
        String password = req.getParameter("password");
        String code = req.getParameter("code");
        String attribute =(String) req.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        UserService userService = new UserServiceImpl();
        User user = new User();
        user.setTelephone(telephone);
        user.setPassword(password);
        User telPwd = userService.findTelPwd(user);


        //从前端取到的数据，要先判断是否为空，如果为空，返回登入页面
        if(telephone!=null&!telephone.equals("")){
           //判断是否为空
            if(userService.existsTelephone(user.getTelephone())!=null){
                if(telPwd!=null & code.equals(attribute)){
                        //为了实现弹窗
                        String s = JSON.toJSONString(1);
                        resp.getWriter().write(s);

               }else {
                    String s = JSON.toJSONString(0);
                    resp.getWriter().write(s);
                   /*req.getRequestDispatcher("/pages/login.jsp").forward(req,resp);*/
                }
            }else {
                String s =JSON.toJSONString(2);
                resp.getWriter().write(s);
                /*req.getRequestDispatcher("/pages/loginFail.jsp").forward(req,resp);*/
            }
        }else {
            String s = JSON.toJSONString(3);
            resp.getWriter().write(s);
           /* req.getRequestDispatcher("pages/login.jsp").forward(req,resp);*/
        }


    }
}
